//
//  KVOObject.m
//  lvfj
//
//  Created by lvfeijun on 2022/5/20.
//  Copyright © 2022 Goudu KuaiEx Technology(Shenzhen)Co.,ltd. All rights reserved.
//

#import "KVOObject.h"

@implementation KVOObject
#pragma mark mj_header
- (void)setEnableHeaderRefresh:(BOOL)enableHeaderRefresh
{
    [super setEnableHeaderRefresh:enableHeaderRefresh];
    if (self.tableView.mj_header) {
        [self.tableView.mj_header addObserver:self forKeyPath:@"backgroundColor" options:NSKeyValueObservingOptionNew context:nil];
        self.tableView.mj_header.backgroundColor = UIColor.redColor;
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"backgroundColor"]) {
        id news = [change objectForKey:NSKeyValueChangeNewKey];
        DDLogDebug(@"====attributedText= %@", news);
    }
}

#pragma mark webview

-(void)setKVO{
//    NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
//    [p1 addObserver:self forKeyPath:@"age" options:options context:nil];
    [self.wkWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {

        @weakify(self);
        [self.wkWebView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            CGFloat height = [result floatValue];
            @strongify(self);
            if (height != self.webViewHeight) {
                self.webViewHeight = MAX(height, self.webViewHeight);
                [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]];

            }

            //监听一次必须移除，以免滑动不断调用
            [self removeObserverForWebViewContentSize];
        }];
    }
}
- (void)removeObserverForWebViewContentSize
{
    if (self.obserArray.count) {
        [self.obserArray removeObject:@"contentSize"];
        [_wkWebView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    }
}

@end
